const tree = [
    {
        id: 0,
        name: 'root',
        children: [
            {
                id: 1,
                name: 'child1',
                children: [
                    {
                        id: 4,
                        name: 'child1-1',
                        children: []
                    },
                    {
                        id: 5,
                        name: 'child1-2',
                        children: []
                    }
                ]
            },
            {
                id: 2,
                name: 'child2',
                children: [
                    {
                        id: 6,
                        name: 'child2-1',
                        children: [
                            {
                                id: 8,
                                name: 'child2-1-1',
                                children: []
                            }
                        ]
                    }
                ]
            },
            {
                id: 3,
                name: 'child3',
                children: [
                    {
                        id: 7,
                        name: 'child3-1',
                        children: []
                    }
                ]
            }
        ]
    }
]

//树转列表   //存放取出来的对象
function treeToList(tree,result = [],parent=null) {
    
    tree.forEach(item => {
        //浅拷贝，防止操作影响源数据
        const element = {...item};
        //添加parentId属性
        element.parentId = parent;

        result.push(element); //[{0:{1:{4,5},2{6:{8}},3:{7}}}]  result=[0]
        if(element.children.lentgh!=0){
            treeToList(element.children,result,element.id);
        };
        delete element.children;
    });

    return result; 
}
const list = treeToList(tree);

/* 使用tree，list查找id为8的数据 */
// console.log(list.find(e=>e.id==8));

//tree
function listToMap(list) {
    /* const result = {};
    list.forEach(e=>{
        result[e.id] = e;
    });
    return result; */
    return list.reduce((prev,curr)=>((prev[curr.id]=curr),prev),{});
}

const map = listToMap(list);
// console.log(map[8]);